﻿using smp.QueryDb.Structure;

namespace smp.QueryDb.Executing
{
    public class Delete
    {
        private readonly Command _command;
        private readonly Table _table;
        private Filter _filter;

        public Delete(Table table)
        {
            if (table == null)
                throw Helper.Error("Cannot initialise Delete with null table");
            if (table.IsReadOnly)
                throw Helper.Error("Cannot delete data in a read only table or view");

            _table = table;
            _command = new Command();
            _command.CommandBuilder.AppendFormat("DELETE {0} ", table.Declaration);
        }

        public Delete Where(Filter filter)
        {
            _filter = filter;
            return this;
        }

        internal void AppendCommandText(string format, params object[] args)
        {
            _command.CommandBuilder.AppendFormat(format, args);
        }

        internal void AddParameter(IParameter parameter)
        {
            _command.AddParameter(parameter);
        }

        internal ICommand GetCommand(IDbAdapter adapter)
        {
            if(_command.CommandBuilder.ToString().EndsWith(","))
            {
                _command.CommandBuilder.Remove(_command.CommandBuilder.Length - 1, 1);
            }
            if (_filter != null)
            {
                _command.CommandBuilder.Append(" WHERE ");
                _filter.Structure.ResetParameters();
                var parameterIndex = 0;
                _filter.Structure.AppendExecuteCommandBuilder(_command, parameterIndex, _table, adapter, _command.CommandBuilder.Length - 1);
                _command.AddParameters(_filter.Structure.Parameters);
            }
            else
            {
                InstanceFactory.Log.Warning("No filter has been defined for Delete command, all records will be deleted.");
            }
            return _command;
        }
    }
}
